package com.lzm.back.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzm.back.entity.Event;
import com.lzm.back.entity.EventCategory;
import com.lzm.back.entity.EventCategoryRelation;
import com.lzm.back.service.EventCategoryRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/relations")
public class EventCategoryRelationController {

    @Autowired
    private EventCategoryRelationService relationService;

    @GetMapping("/search")
    public PageInfo<EventCategoryRelation> searchRelations(
            @RequestParam(required = false) String categoryName,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size) {
        PageHelper.startPage(page, size);

        List<EventCategoryRelation> list = relationService.searchRelations(categoryName);
        return new PageInfo<>(list);
    }

    @GetMapping("/categories")
    public List<EventCategory> getAllCategories() {
        return relationService.getAllCategories();
    }

    @GetMapping("/events")
    public List<Event> getAllEvents() {
        return relationService.getAllEvents();
    }

    @GetMapping("/{categoryId}")
    public List<Long> getEventIdsByCategoryId(@PathVariable Long categoryId) {
        return relationService.getEventIdsByCategoryId(categoryId);
    }

    @PutMapping
    public void saveRelation(@RequestBody Map<String, Object> request) {
        Long categoryId = Long.parseLong(request.get("categoryId").toString());
        List<Long> eventIds = (List<Long>) request.get("eventIds");
        relationService.saveRelation(categoryId, eventIds);
    }

    @DeleteMapping("/{id}")
    public void deleteRelation(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("Invalid ID: " + id);
        }
        relationService.deleteRelation(id);
    }

    @DeleteMapping("/batch")
    public void batchDeleteRelations(@RequestBody List<Long> ids) {
        relationService.batchDeleteRelations(ids);
    }
}